package com.betterjr.modules.api;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.dubbo.config.annotation.Reference;
import com.betterjr.common.web.AjaxObject;
import com.betterjr.common.web.AjaxRemoteApiParam;
import com.betterjr.common.web.ControllerExceptionHandler;
import com.betterjr.common.web.ControllerExceptionHandler.ExceptionHandler;
import com.betterjr.common.web.Servlets;
import com.betterjr.modules.account.dubbo.interfaces.ICustBaseConfigureService;
import com.betterjr.modules.account.dubbo.interfaces.ICustLoginService;
import com.betterjr.modules.account.entity.CustOperatorInfo;
import com.betterjr.modules.risk.api.IRemoteApiService;

@Controller
@RequestMapping("/Scf/RemoteApi")
public class RemoteApiController {

    private static final Logger logger = LoggerFactory.getLogger(RemoteApiController.class);

    /*@Reference(interfaceClass = IRemoteApiService.class)
    private IRemoteApiService remoteApiService;*/

    @Reference(interfaceClass = IRemoteApiService.class)
    private IRemoteApiService remoteApiService;

    @Reference(interfaceClass = ICustBaseConfigureService.class)
    private ICustBaseConfigureService configureService;

    @Reference(interfaceClass = ICustLoginService.class)
    private ICustLoginService custLoginService;

    @RequestMapping("/eclAgreement")
    @ResponseBody
    public String operatorAgreement(HttpServletRequest request) {

        AjaxRemoteApiParam param = fillRemoteParam(request);

        logger.info("远程接口调用,入参:" + param);

        if (!checkParam(param)) return AjaxObject.newError("请求接口校验不通过").toJson();

        return ControllerExceptionHandler.exec(new ExceptionHandler() {
            @Override
            public String handle() {
                return remoteApiService.operatorAgreement(param);
            }
        }, "远程接口调用失败", logger);
    }

    private AjaxRemoteApiParam fillRemoteParam(HttpServletRequest request) {

        AjaxRemoteApiParam param = new AjaxRemoteApiParam();

        if (request != null) {
            Map<String, Object> anMap = Servlets.getParametersStartingWith(request, "");
            BetterBeanUtils.copyProperties2Bean(param, anMap);
        }

        return param;

    }

    public boolean checkParam(AjaxRemoteApiParam param) {

        CustOperatorInfo info = configureService.findOperatorByCustIdentifition(param.getCustIdentifition(),
                param.getServicerType(), param.getUserCode());
        if (param.isLogin()) custLoginService.saveFormLogin(info);
        return info == null ? false : true;

    }

}
